package cat.joronya.supermanager.privateleague;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.service.JoinPrivateLeagueHandler;
import cat.joronya.supermanager.service.PrivateLeagueHandler;
import cat.joronya.supermanager.service.SupermanagerServiceHelper;
import cat.joronya.supermanager.team.MyTeamsProvider;
import cat.joronya.supermanager.team.Team;

/**
 * Activitat per inscriure a una lliga privada.
 * @author pol
 */
public class JoinPrivateLeagueActivity  extends ListActivity 
{
	// pel Log
	private static final String TAG = "supermanager";
	
	private static final int PROGRESS_JOIN = 1;
	
	// the progress dialog
	ProgressDialog progress = null;
	
	private int id_pri = 0;
	private String name = "";
	
	// jornada que estem mostrant
    private int day = 0;
    private int nextDay = 0;
    
    //private ArrayList<Team> teams;
    private Team[] teams;
    private ItemsAdapter adapter;
    
    /** 
	 * Called when the activity is first created. 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.join_private_league);
    
		id_pri = getIntent().getIntExtra("cat.joronya.supermanager.privateleagues.id_pri", 0);
		name = getIntent().getStringExtra("cat.joronya.supermanager.privateleagues.name");
	
		// afegim name al label
		TextView textView = (TextView) findViewById(R.id.private_league_join_label);
		textView.setText(getString(R.string.private_league_join_label, name));
		
		// amaguem el ProgressBar
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.private_league_join_loading);
        progressBar.setVisibility(View.INVISIBLE);
        
        // If no data was given in the intent, then use our default content provider.
        Intent intent = getIntent();
        Uri plUri = getIntent().getData();
        if( plUri == null) {
        	plUri = Supermanager.PrivateLeague.CONTENT_URI;
            intent.setData(Supermanager.PrivateLeague.CONTENT_URI);
        }
        
        // retrieve day and status
        Cursor duetimeCursor = getContentResolver().query(Supermanager.Home.CONTENT_URI, 
        		Supermanager.Home.PROJECTION,
        		null, null, Supermanager.Home.DEFAULT_SORT_ORDER);
        if( duetimeCursor.moveToFirst() )
        {
        	day = duetimeCursor.getInt(1);
        	nextDay = duetimeCursor.getInt(5);
        }
        duetimeCursor.close();
	
        MyTeamsProvider myTeamsProvider = new MyTeamsProvider();
		Cursor teamsCursor = myTeamsProvider.getTeamList(this, ""+day, ""+nextDay);
        
		//teams = new ArrayList<Team>();
		teams = new Team[teamsCursor.getCount()];
		while( teamsCursor.moveToNext() )
		{
			Team team = new Team();
			team.setIdEqu(teamsCursor.getString(1));
			team.setName(teamsCursor.getString(2));
			teams[teamsCursor.getPosition()] = team;
		}
		teamsCursor.close();
		myTeamsProvider.closeDataBase();
        
		getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        
		adapter = new ItemsAdapter(this,teams);
		setListAdapter(adapter);
	}
	
	/**
     * Metode on creem el/s dialeg de la activity.
     * Nomes en tenim un, passem del id.
     */
    @Override
    public Dialog onCreateDialog(int id)
    {
    	progress = ProgressDialog.show(this, "", 
    		getResources().getString(R.string.private_league_join_progress_joining), true);
    	progress.setCancelable(false);
    	return progress;
    }
	
	@Override
	protected void onListItemClick (ListView l, View v, int position, long id)
	{
		CheckedTextView tv = (CheckedTextView) v;
		
		// canviem l'estat de seleccio
		toggle(tv);
		teams[position].toggle();
	}
	
	public void toggle(CheckedTextView v) 
	{
		v.setChecked(!v.isChecked());
	}
	
	private class ItemsAdapter extends BaseAdapter 
	{
		private Team[] teams;

		public ItemsAdapter(Context context, Team[] theTeams) 
		{
			this.teams = theTeams;
		}

		// @Override
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.join_private_league_row, null);
			}
			CheckedTextView post = (CheckedTextView) v.findViewById(R.id.private_league_join_row);
			post.setText(teams[position].getName());

			return v;
		}

		public int getCount() 
		{
			return teams.length;
		}

		public Object getItem(int position) 
		{
			return position;
		}

		public long getItemId(int position) 
		{
			return position;
		}
	}
	
	public void joinPrivateLeague(View view)
	{
		Log.d(TAG, "joinPrivateLeague...");
		
		String  equips = "";
		for(int i=0;i<teams.length;i++) 
		{
			if( teams[i].isSelected() )
			{
				if( !equips.equals("") )
					equips += ",";
				equips += teams[i].getIdEqu();
			}
		}
		
		// si no han seleccionat equips, error
		if( equips.equals("") )
		{
			Toast.makeText(this, R.string.private_league_join_select_team, Toast.LENGTH_LONG).show();
			return;
		}
		
		final String equipsToJoin = equips;
		
		// check als passwords
		EditText passView = (EditText)findViewById(R.id.private_league_join_input);
		final String pass = passView.getText().toString();
		
		// Nota: la clave no s'empra. Em salto un pas comparat amb el web. No cal demanar password... tenen un bug.
		// Hi han tres passos:
		// -cercar lliga
		// -al triar lliga, demana password per anar a triar equips a inscriure (pas que em salto)
		// -inscriure equips, surten equips teus q checkejes quin vols inscriure, no cal password
		
		// ocultem el teclat
    	InputMethodManager imm = (InputMethodManager)getSystemService(
    		      Context.INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(passView.getWindowToken(), 0);
		
		// mostrem el ProgressDialog
		showDialog(PROGRESS_JOIN);
        
		new Thread( new Runnable()
		{
			public void run()
			{
				// arranquem el service amb el helper
				SupermanagerServiceHelper.getInstance(JoinPrivateLeagueActivity.this).
					joinPrivateLeague(handler, ""+id_pri, equipsToJoin, pass);
			}
		}).start();
	}
	
	JoinPrivateLeagueHandler handler = new JoinPrivateLeagueHandler()
	{

		@Override
		public void joinOk(Message msg) 
		{
			// mostrem join ok
	        progress.setMessage(getString(R.string.private_league_join_progress_refresh));
	        
			// enviar a parsejar lligues privades per veure canvis
	        SupermanagerServiceHelper.getInstance(JoinPrivateLeagueActivity.this).
	        	getPrivateLeagues(privateLeagueHandler);
		}
		
		@Override
		public void wrongPassword(Message msg)
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_JOIN);
	        
	        // mostrem error
	        Toast.makeText(JoinPrivateLeagueActivity.this, 
	        		R.string.private_league_join_wrong_password_error, Toast.LENGTH_LONG).show();
	        
	        // situem el focus al camp passwd
	        EditText passView = (EditText)findViewById(R.id.private_league_join_input);
	        passView.setText("");
	        passView.requestFocus();
		}
		
		@Override
		public void maxTeamReached(Message msg)
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_JOIN);
	        
	        // mostrem error
	        Toast.makeText(JoinPrivateLeagueActivity.this, 
	        		R.string.private_league_join_max_team_reached_error, Toast.LENGTH_LONG).show();
		}
		
		@Override
		public void matTeamPerPlayerReached(Message msg)
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_JOIN);
	        
	        // mostrem error
	        Toast.makeText(JoinPrivateLeagueActivity.this, 
	        		R.string.private_league_join_max_team_per_player_reached_error, Toast.LENGTH_LONG).show();
		}

		@Override
		public void authError() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_JOIN);
	        
	        // mostrem error
	        Toast.makeText(JoinPrivateLeagueActivity.this, 
	        		R.string.private_league_join_auth_error, Toast.LENGTH_LONG).show();
		}

		@Override
		public void otherError() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_JOIN);
	        
	        // mostrem error
	        Toast.makeText(JoinPrivateLeagueActivity.this, 
	        		R.string.private_league_join_other_error, Toast.LENGTH_LONG).show();
		}

		@Override
		public void connectivityError() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_JOIN);
	        
	        // mostrem error
	        Toast.makeText(JoinPrivateLeagueActivity.this, 
	        		R.string.private_league_join_connectivity_error, Toast.LENGTH_LONG).show();
		}
	};
	
	PrivateLeagueHandler privateLeagueHandler = new PrivateLeagueHandler() 
	{
		@Override
		public void authError() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_JOIN);
	        
	        // mostrem error
	        Toast.makeText(JoinPrivateLeagueActivity.this, 
	        		R.string.private_league_join_auth_error, Toast.LENGTH_LONG).show();
		}

		@Override
		public void otherError() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_JOIN);
	        
	        // mostrem error
	        Toast.makeText(JoinPrivateLeagueActivity.this, 
	        		R.string.private_league_join_other_error, Toast.LENGTH_LONG).show();
		}

		@Override
		public void connectivityError() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_JOIN);
	        
	        // mostrem error
	        Toast.makeText(JoinPrivateLeagueActivity.this, 
	        		R.string.private_league_join_connectivity_error, Toast.LENGTH_LONG).show();
		}
		
		@Override
		public void privateLeagueParsed() 
		{
			// amaguem el ProgressDialog
	        dismissDialog(PROGRESS_JOIN);
	        
	        // mostrem error
	        Toast.makeText(JoinPrivateLeagueActivity.this, 
	        		R.string.private_league_join_refresh, Toast.LENGTH_LONG).show();

	        // sortir de l'activity
	        JoinPrivateLeagueActivity.this.finish();
		}
	};
}
